package com.gruuf.done.web;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.StrutsStatics;

public class LoginInterceptor extends AbstractInterceptor {

    public static final String LOGIN_URL = "loginUrl";

    public String intercept(ActionInvocation invocation) throws Exception {
        UserService userService = UserServiceFactory.getUserService();
        if (userService.isUserLoggedIn()) {
            return invocation.invoke();
        } else {
            ActionContext context = invocation.getInvocationContext();
            HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST);
            String url = request.getRequestURI();
            context.getSession().put(LOGIN_URL, userService.createLoginURL(url));
            return Action.LOGIN;
        }
    }

}
